import Vue from "vue";
import Router from "vue-router";
import * as staticView from "./staticView";
import * as adminView from "./adminView";
import * as layouts from "./layouts";
import store from "@/store";
import Cookies from "js-cookie";
import NProgress from "@/utils/nprogress";
import { isDev, rootPath } from "@/configurations";
import { translateTreeToData1 } from "@/utils/parentSon";
import { getQueryVariable } from "@/utils/getQueryVariable";
// import { route_psychz, route_FrontPage } from "@/router/isDefalutView";
// import { settings } from "nprogress";
Vue.use(Router);

let staticList = Object.values(staticView); // 静态路由列表
let layoutList = Object.values(layouts); //布局列表
let adminList = Object.values(adminView); //管理端页面列表
let routes = [];
let viewList = isDev ? [...staticList, ...adminList] : [...staticList];
for (const view of viewList) {
  // 组装路由与布局
  if (!view.layout) {
    routes.push(view);
  } else {
    const layout = layoutList.find(i => i.name === view.layout);
    if (layout) {
      if (!layout.meta)
        layout.meta = {
          layout: view.layout
        };
      layout.children.unshift(view);
      if (view.meta.isDefault) {
        layout.redirect = view.path;
      }
      view.meta.layout = view.layout;
      if (layout.children.find(i => i?.meta?.show)) {
        layout.meta.show = true;
      }
    }
  }
}
routes = [...routes, ...layoutList];
export { routes };

export const menuSon = store.state.user.menuList;
export const roleNow = store.state.user.role;
var add = false;

const loadView = viewPath => {
  return function(resolve) {
    require([`@/${viewPath}`], resolve);
  };
};

/**
 * @name 动态添加路由
 * @param {*} list
 */
export async function setAddRoutes(list) {
  //动态路由
  let routeList = menuSon;

  routeList.forEach(element => {
    element.meta = JSON.parse(element.meta);
    if (element.layout == "Dashboard") {
      element.components = JSON.parse(element.components);
      element.components.content = loadView(`${element.components.content}`);
      element.components.left = loadView(`${element.components.left}`);
      element.components.right = loadView(`${element.components.right}`);
    } else {
      element.component = loadView(`${element.components}`);
      delete element.components;
    }
  });
  for (const view of routeList) {
    // 组装路由与布局
    if (!view?.layout) {
      if (view.parent) {
        //多层路由
        routeList.forEach(e => {
          if (e.id == view.parent) {
            if (e?.children) {
              e.children.push(view);
            } else {
              e.children = [view];
            }
          }
        });
      }
      //   routes.push(view);
    } else {
      const layout = layoutList.find(i => i.name === view.layout);
      if (layout) {
        if (!layout.meta)
          layout.meta = {
            layout: view.layout
          };
        layout.children.unshift(view);
        if (view.meta.isDefault) {
          layout.redirect = view.path;
        }
        view.meta.layout = view.layout;
        if (layout.children.find(i => i?.meta?.show)) {
          layout.meta.show = true;
        }
      }
    }
  }

  if (!add) {
    isDefaultRoute();
    resetRouter(routes);
  } else {
    add = true;
  }
}
export const roleName = () => {
  return store.state?.user?.role?.roleName;
};
export const isDefaultRoute = () => {
  const defaultRoute = translateTreeToData1(routes).find(
    i => i?.meta?.isDefault && i.layout
  ); // 查找默认跳转
  //   console.log(translateTreeToData1(routes));
  //   console.log("defaultRoute");
  //   console.log(defaultRoute);
  if (defaultRoute) {
    routes.unshift({
      path: "/",
      redirect: defaultRoute.path
    });
  }
};

const createRouter = () =>
  new Router({
    mode: "history", // require service support
    base: rootPath,
    scrollBehavior: () => ({ y: 0 }),
    routes: routes
  });

const router = createRouter();

export function resetRouter(list) {
  const newRouter = new Router({
    mode: "history", // require service support
    base: rootPath,
    scrollBehavior: () => ({ y: 0 }),
    routes: list
  });
  router.matcher = newRouter.matcher; // reset router
}
router.beforeEach((to, from, next) => {
  do {
    // let token = getQueryVariable("token");
    // if (token) {
    //   store.state.yzyToken = token;
    // }
    // if (to.name == "login" && token) {
    //   //   Cookies.set("logined_xinxifabu", "");
    //   next();
    //   return;
    // }
    if (isDev) break;
    const logined = Cookies.get("logined_xinxifabu");

    if (!logined) {
      NProgress.start();
      if (
        staticList.filter(e => e.name != "404").find(i => i.name == to.name)
      ) {
        next();
        return;
      }
      if (to.name !== "login") {
        next({
          path: "/login"
        });
        return;
      }
      next();
      return;
    }
    if (to.name === "login") {
      NProgress.start();
      next({
        path: "/"
      });
      return;
    }
  } while (false);
  NProgress.start();
  if (to.name == "403") {
    alert("当前账号无权限访问该页面，如需要请联系管理员配置权限！");
    return;
  } else {
    next();
  }
});

router.afterEach(() => {
  window.scrollTo(0, 0);
  NProgress.done();
});
// if (!isDev) {
setAddRoutes(); //添加路由
// }

export default router;
